package org.campuscontent.model;

import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.campuscontent.config.Config;
import org.campuscontent.main.MainFrame;

@SuppressWarnings( {"deprecation", "unused"} )
public class AllocTable extends JPanel implements ActionListener,
		 MouseListener {

	public MainFrame mf;
	BorderLayout borderLayout1 = new BorderLayout();
	JPanel pane = new JPanel();
	JPanel jPanel2 = new JPanel();
	JPanel header = new JPanel();
	JPanel header2 = new JPanel();
	JTextField[] newRowTextfield = new JTextField[3];
	JPanel newRowPanel = new JPanel();

	// Vector<String> allRows = new Vector();
	public String allRows = "";
	String rowSpliter = "R-O-W";
	int al = 10; 
	int ao = 10; 
	int width = 30;
	int height = 25;

	boolean enable = true;

	public AllocTable(MainFrame mf) {

		this.mf = mf;
		enableEvents(AWTEvent.WINDOW_EVENT_MASK);
		try {
			jbInit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.addMouseListener(this);
	}

	public void addComponent(JPanel parent, Component child, String constraints) {
		if (constraints.equals("")) {
			parent.add(child);
		} else {
			parent.add(child, constraints);
		}
	}

	
	
	// Component initialization
	private void jbInit() throws Exception {
		
	    ImageIcon iconAccept  =  new ImageIcon(this.getClass().getResource("/org/campuscontent/images/toolbar/accept.gif"));

		GridLayout grid = new GridLayout(0, 1);
		grid.setVgap(0);
		this.setLayout(grid);
		// this.setBorder(BorderFactory.createLineBorder(Color.red ));
		String[] labelText = { Config.Transition, Config.Source,
				Config.Character, Config.End };
		header.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 2));

		addComponent(header, pseudoLabel(15, labelText[0], header.getBackground()), "");
		for (int i = 1; i <= 3; i++) {
			addComponent(header, pseudoLabel(10, labelText[i], header
					.getBackground()), "");
		}
		this.add(header);

			// prepare for the new Row
			newRowPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 2));
			newRowPanel.setBorder(BorderFactory.createLoweredBevelBorder());
			newRowPanel.setBackground(Config.ColorAllocationTableNewRowPanel);
			JTextField newRow = pseudoLabel(15, Config.NewTransitionRow,
					newRowPanel.getBackground());
			addComponent(newRowPanel, newRow, "");
			String[] tooltips = { Config.TooltipSource, Config.TooltipEntry,
					Config.TooltipEnd };
			for (int i = 1; i <= newRowTextfield.length; i++) {
				String tipp = "";
				if (i - 1 < tooltips.length) {
					tipp = tooltips[i - 1];
				}
				newRowTextfield[i - 1] = textfield(10, "", tipp, Color.WHITE, true);
				addComponent(newRowPanel, newRowTextfield[i - 1], "");
			}
			// JLabel ok = new JLabel();
			JButton ok = new JButton();
			ok.setIcon(iconAccept);
			ok.setBorderPainted(false);
			ok.setMargin(new Insets(0, 0, 0, 0));
			ok.setBackground(newRowPanel.getBackground());
			// ok.setSize(0, 0);
			ok.addActionListener(this);
			newRowPanel.add(ok);
			this.add(newRowPanel);
		
	}


	public JTextField pseudoLabel(int cols, String text, Color background) {
		JTextField textfield = new JTextField(cols);
		textfield.setEditable(false);
		textfield.setBackground(background);
		textfield.setBorder(null);
		// textfield.setBounds(pos * width + al, 0, width, height);
		textfield.setText(text);
		//textfield.setFont(Fonts.GUIActualFont);
		textfield.setMargin(new Insets(0, 0, 0, 0));
		return textfield;
	}

	
	public JTextField textfield(int cols, String text, String tooltip,
			Color background, boolean al) {
		JTextField textfield = new JTextField(cols);
		textfield.setBackground(background);
		textfield.setText(text);
		textfield.setToolTipText(tooltip);
//		textfield.setFont(Fonts.GUIActualFont);
		textfield.setMargin(new Insets(0, 0, 0, 0));
		if (al) {
			textfield.addActionListener(this);
		}
		return textfield;
	}

	public void mouseClicked(MouseEvent e) {
		System.err.println(e.getPoint());
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	
	public void addRow(String text) {
		AllocTableRow newRow = new AllocTableRow(this, text);
		allRows = allRows + text + Config.ALLOC_TABLE_SPLITOR;
		this.add(newRow);
	}

//	public void addComponent(JPanel parent, Component child, String constraints) {
//		Vector components = mf.getComps();
//		if (constraints.equals("")) {
//			parent.add(child);
//		} else {
//			parent.add(child, constraints);
//		}
//		components.add(child);
//	}

	
	public void replaceRow(int index,String strInput)
	{
		String str[] = allRows.split(Config.ALLOC_TABLE_SPLITOR);
		allRows = "";
		int rowCount = str.length;

		str[index] = strInput;
	
		for (int i = 0; i < rowCount; i++)
			allRows = allRows + str[i] + Config.ALLOC_TABLE_SPLITOR;

		
	}
	
	public void setAllRowToAllocTable(String allRow)
	{
		String str[] = allRow.split(Config.ALLOC_TABLE_SPLITOR);
		for (int i = 0;  i<str.length; i++)
		{
			addRow(str[i]);
		}
	}
	
	public void deleteRow(int rownumber) {
		// allRows.remove(rownumber);

		String str[] = allRows.split(Config.ALLOC_TABLE_SPLITOR);
		allRows = "";
		int rowCount = str.length;

		for (int i = rownumber; i < str.length; i++) {
			if (i != rowCount - 1) {
				str[i] = str[i + 1];
			} else {
				if (i == 0)
					str[i] = "";
				else {
					str[i] = "";
				}
				rowCount--;
			}
		}

		for (int i = 0; i < rowCount; i++)
			allRows = allRows + str[i] + Config.ALLOC_TABLE_SPLITOR;

		rownumber += 2;
//		int rows = this.countComponents();
//		if (rownumber < 1 || rownumber > rows) 
//		{
//		} 
//		else {
//			Component comp = this.getComponent(rownumber);
//			if (comp instanceof AllocTableRow) {
//				Vector components = getMainFrame().getComps();
//				AllocTableRow row = (AllocTableRow) comp;
//				for (int i = 0; i < row.countComponents(); i++) {
//					if (components.contains(row.getComponent(i))) {
//						components.remove(row.getComponent(i));
//					}
//				}
//			}
			this.remove(rownumber);
	
	}

	public void deleteAllRows() {
			String[] str = allRows.split(Config.ALLOC_TABLE_SPLITOR);
			int rows = str.length;
			int i = 0;
			if ((rows == 1) && (str[0].equals(""))) {
			} else
				while (rows > i) {
					deleteRow(rows - 1);
					rows--;
				}
			
		
	}

	
	public MainFrame getMainFrame() {
		return mf;
	}

    public int getConnectionRowNumber(String con) {
		int row = 0;
		int rows = this.countComponents();
        int zufall = (int) (100 * Math.random());
		int counter = 2;
		while (row == 0 && counter < rows) {
			Component comp = null;
			try {
				comp = this.getComponent(counter);
			} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
				System.err.println("Counter: " + counter);
				System.err.println("Components: " + this.countComponents());
				ex.printStackTrace();
			}
			if (comp instanceof JPanel) {
				JPanel conPanel = (JPanel) comp;
				Component comp2 = conPanel.getComponent(0);
				if (comp2 instanceof JLabel) {
					JLabel conLabel = (JLabel) comp2;
					String conText = conLabel.getText();
					if (conText.equals(con)) {
						row = counter;
					}
				}
			} else {
				System.err.println("Angegebene Reihe ist kein Panel!");
			}
			counter++;
		}
		return row;
	}


	public boolean contains(String con) {
		String str[] = allRows.split(Config.ALLOC_TABLE_SPLITOR);
		// int rows = allRows.length();
		int rows = str.length;

		for (int i = 0; i < rows; i++) {
			// String conText = allRows.get(i);
			String conText = str[i];
			if (conText.equals(con)) {
				return true;
			}
		}
		return false;
	}

	public int getRowIndex(String con) {
		int index = -1;
		String[] str = allRows.split(Config.ALLOC_TABLE_SPLITOR);
		int rows = str.length;
		// int rows = allRows.size();
		for (int i = 0; i < rows; i++) {
			// String conText = allRows.get(i);
			String conText = str[i];
			if (conText.equals(con)) {
				index = i;
			}
		}
		return index;
	}


	public void updateFromAllRows() {

		String[] str = allRows.split(Config.ALLOC_TABLE_SPLITOR);

		// for (int i = 0; i < allRows.size(); i++) {
		if ((str.length == 1) && (str[0].equals(""))) {
		} else
			for (int i = 0; i < str.length; i++) {
				AllocTableRow newRow = new AllocTableRow(
						this, str[i]);
				this.add(newRow);
				// String text = String.valueOf(str[i]);
				// if (contains(text)) {
				// addRow(text);
				// }

			}
	}
	
	public JTextField getFirstColumnTextField(int row) {
		JTextField text = null;
		Component comp = this.getComponent(row);
		if (comp instanceof JPanel) {
			JPanel rowPanel = (JPanel) comp;
			Component comp2 = rowPanel.getComponent(0);
			if (comp2 instanceof JTextField) {
				text = (JTextField) comp2;
			}
		}
		return text;
	}

	public void setEnableAfterSolution(boolean enable) {
		int count = this.countComponents() - 1;
		for (int i = 1; i <= count; i++) {
			JTextField text = null;
			JButton del = null;
			Component comp = this.getComponent(i);
			if (comp instanceof JPanel) {
				JPanel rowPanel = (JPanel) comp;
				Component comp1 = rowPanel.getComponent(1);
				Component comp2 = rowPanel.getComponent(2);
				Component comp3 = rowPanel.getComponent(3);
				Component comp4 = rowPanel.getComponent(4);
				if (comp1 instanceof JTextField) {
					text = (JTextField) comp1;
					text.setEnabled(enable);
				}
				if (comp2 instanceof JTextField) {
					text = (JTextField) comp2;
					text.setEnabled(enable);
				}
				if (comp3 instanceof JTextField) {
					text = (JTextField) comp3;
					text.setEnabled(enable);
				}
				if (comp4 instanceof JButton) {
					del = (JButton) comp4;
					del.setEnabled(enable);
				}
			}
		}
	}

	public void setEditableAfterSolution(boolean enable) {
		int count = this.countComponents() - 1;
		for (int i = 1; i <= count; i++) {
			JTextField text = null;
			JButton del = null;
			Component comp = this.getComponent(i);
			if (comp instanceof JPanel) {
				JPanel rowPanel = (JPanel) comp;
				Component comp1 = rowPanel.getComponent(1);
				Component comp2 = rowPanel.getComponent(2);
				Component comp3 = rowPanel.getComponent(3);
				Component comp4 = rowPanel.getComponent(4);
				if (comp1 instanceof JTextField) {
					text = (JTextField) comp1;
					text.setEditable(enable);
				}
				if (comp2 instanceof JTextField) {
					text = (JTextField) comp2;
					text.setEditable(enable);
				}
				if (comp3 instanceof JTextField) {
					text = (JTextField) comp3;
					text.setEditable(enable);
				}
				if (comp4 instanceof JButton) {
					del = (JButton) comp4;
					del.setEnabled(enable);
				}
			}
		}
	}
	

	public JTextField getTextFieldSource(int row) {
		JTextField textfield = null;
		Component comp = this.getComponent(row);
		if (comp instanceof JPanel) {
			JPanel rowPanel = (JPanel) comp;
			Component comp2 = rowPanel.getComponent(1);
			if (comp2 instanceof JTextField) {
				textfield = (JTextField) comp2;
			}
		}
		return textfield;
	}


	public JTextField getTextFieldEntry(int row) {
		JTextField textfield = null;
		Component comp = this.getComponent(row);
		if (comp instanceof JPanel) {
			JPanel rowPanel = (JPanel) comp;
			Component comp2 = rowPanel.getComponent(2);
			if (comp2 instanceof JTextField) {
				textfield = (JTextField) comp2;
			}
		}
		return textfield;
	}

	public JTextField getTextFieldEnd(int row) {
		JTextField textfield = null;
		Component comp = this.getComponent(row);
		if (comp instanceof JPanel) {
			JPanel rowPanel = (JPanel) comp;
			Component comp2 = rowPanel.getComponent(3);
			if (comp2 instanceof JTextField) {
				textfield = (JTextField) comp2;
			}
		}
		return textfield;
	}

	public String rowToString(int rownumber) {
		String[] parts = { "((", ",", ")," }; // initialized to catch a
		// exception

		Component comp = this.getComponent(rownumber);
		if (comp instanceof JPanel) {
			JPanel rowPanel = (JPanel) comp;
			for (int i = 1; i < rowPanel.countComponents(); i++) {
				Component compTextField = rowPanel.getComponent(i);
				if (compTextField instanceof JTextField) {
					JTextField textfield = (JTextField) compTextField;
					parts[i - 1] += textfield.getText();
				}
			}
		}
		String row = parts[0] + parts[1] + parts[2] + ")";
		return row;
	}

	public String inputRowToString(String[] comps) {
		String[] parts = { "((", ",", ")," };
		for (int i = 0; i < 3; i++) {
			parts[i] += comps[i];

		}
		String row = parts[0] + parts[1] + parts[2] + ")";
		return row;
	}

	public void clear() {
		int rows = this.countComponents();
		// row one is the header and will not be deleted!
		for (int i = 2; i < rows; i++) {
			deleteRow(2);
		}
	}

	public void actionPerformed(ActionEvent e) {
		if (!enable)
			return;

		Component comps[] = new Component[3];
		JTextField textfields[] = new JTextField[3];
		String contents[] = new String[3];
		for (int i = 1; i <= 3; i++) {
			comps[i - 1] = newRowPanel.getComponent(i);
			if (comps[i - 1] instanceof JTextField) {
				textfields[i - 1] = (JTextField) comps[i - 1];
				contents[i - 1] = textfields[i - 1].getText().trim();

			}
		}

		if ((contents[0].length() == 0) || (contents[1].length() == 0)
				|| (contents[2].length() == 0)) {
			JOptionPane.showMessageDialog(null, "please fill all inputs");
		} else {
			String str = inputRowToString(contents);
			if (!contains(str)) {
				addRow(str);
				mf.templateBase.allocScrollPane.validate();
				for (int i = 0; i < 3; i++) {
					textfields[i].setText("");
				}
			} else {
				JOptionPane.showMessageDialog(null, "Same input found!");
			}
		}

	}
	


	public String getAllRows() {
		return allRows;
	}

	public void setAllRows(String allRows) {
		this.allRows = allRows;
	}
}
